package com.ggg.clothesshop.service.IMPL;

import com.ggg.clothesshop.mapper.OrdersMapper;
import com.ggg.clothesshop.model.Orders;
import com.ggg.clothesshop.service.OrdersService;
import com.ggg.clothesshop.utils.GetNow;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class OrdersServiceIMPL implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public ArrayList<Orders> selectOrdersByUser(int orderNum, int userid) {
        return ordersMapper.selectOrdersByUser(orderNum, userid,"购物车");
    }

    @Override
    public int addCartOrder(Orders order) {

        order.setOrderstatus("购物车");
        //查询是否有老的购物车订单和新的订单货物相同
        Orders oldOrder = ordersMapper.selectSameOrder(order);
        if(oldOrder==null){ //没有则...
            if(ordersMapper.selectCartTotal(order)>=20){ //判断购物车是否已满
                return -1;
            }else {
                order.setOrderdate(GetNow.getNow());
                return ordersMapper.insertSelective(order);
            }
        }else{ //有则合并
            oldOrder.setProductnum(order.getProductnum()+oldOrder.getProductnum());
            return ordersMapper.updateByPrimaryKeySelective(oldOrder);
        }
    }

    @Override
    public Object selectByPage(int pageNum, int pageSize, int userid) {
        PageHelper.startPage(pageNum, pageSize);
        ArrayList<Orders> orders = ordersMapper.selectByUser(userid,"购物车");
        PageInfo result = new PageInfo(orders);
        return result;
    }

    @Override
    public Object selectCartByPage(int pageNum, int pageSize, int userid) {
        PageHelper.startPage(pageNum, pageSize);
        ArrayList<Orders> orders = ordersMapper.selectCartByUser(userid,"购物车");
        PageInfo result = new PageInfo(orders);
        return result;
    }

    @Override
    public int deleteOrderById(int orderid) {
        return ordersMapper.deleteByPrimaryKey(orderid);
    }

    @Override
    public int updateOrder(Orders order) {
        return ordersMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public int addOrder(Orders order) {
        order.setOrderdate(GetNow.getNow());
        return ordersMapper.insertSelective(order);
    }

    @Override
    public int selectLastInsertId() {
        return ordersMapper.selectLastInsertId();
    }

    @Override
    public Orders selectOrderById(Integer orderid) {
        return ordersMapper.selectByPrimaryKey(orderid);
    }
}
